package cn.tedu._05weibo.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户登录状态校验拦截器
 */
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("用户登录校验拦截器执行preHandle方法");
        //未登录，跳转到登录页面
        HttpSession session = request.getSession();
        if (session.getAttribute("user") == null){
            response.sendRedirect("/login.html");
            return false;
        }
        //已登录，放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.debug("用户登录校验拦截器执行postHandle方法");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug("用户登录校验拦截器执行afterCompletion方法");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
